package com.zzyl.framework.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断当前请求是否为handler()[所有@XxxMapping注解的方法 处理器]
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 1.获取请求头的token
        String token = request.getHeader("authorization");
        // 2.token 为空或解析失败, 响应401
        if (ObjectUtil.isEmpty(token) || tokenService.parseToken(token).isEmpty()) {
            throw new RuntimeException("认证失败!");
        }
        // 3.获取用户ID userId
        Claims claims = tokenService.parseToken(token);
        Long userId = claims.get("userId", Long.class);
        // 4.userId==null, 响应401
        if (ObjectUtil.isEmpty(userId)) {
            throw new RuntimeException("认证失败!");
        }
        // 5.把userId保存到ThreadLocal(UserThreadlocal)
        UserThreadLocal.set(userId);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocal.remove();
    }
}
